angular.module('start.user.auth.authguide.ctrl', [])

  .controller('authguideCtrl', function($scope, $timeout, $$JobService,$ionicActionSheet,$$cordovaImagePicker,$$cordovaCamera, $$UploadImageService, $ionicPopup, $ionicScrollDelegate,$$CityService, $ionicModal, $rootScope, $stateParams, $$UserAuthService, $location, $ionicLoading) {
    console.log("authguideCtrl");

    $scope.step = 1;
    $scope.topstep = 1;

    $scope.authguideData = {

      job: '请选择', //0
      region: '', //0
      regionName: '请选择', //0
      // contactPhone: $rootScope.userData.telephone, //"string"
      weChat: "", //"string
      displayPic: "gg.jpg",
      lifePic: "", //"string" 图片数组
      hotId: "",
      serviceCity: '-1', //0
      serviceCityName: "请选择",
      // serviceCityName: "上海,北京,天津,深圳,广州,昆明,大理,丽江,武汉,呼和浩特,包头,上海,洛杉矶",
      serviceRoute: "", //"string" #隔开
      serviceContent: "", //"string"
      introduce: "", //"string"
      servicePrice: null, //"string"
      tourGuideCertificationPic: "", //"string"

      grade: 0, //0

    };

    var hotCatalogData_var = [];
    hotCatalogData_var = JSON.parse(JSON.stringify($rootScope.hotCatalogData));

    $scope.authguideDataServerCate = hotCatalogData_var;

    $scope.displayPicBase64Data = "";
    $scope.tourGuideCertificationPicBase64Data = "";




    $scope.subauthguide = function() {
      if ($scope.validForm2()) {
        $scope.step = 2;
        $ionicLoading.show({
          template: '上传中...'
        });
        for (var i in $scope.gLifePicUrls) {
          $scope.gLifePicUrl += $scope.gLifePicUrls[i].src;
          if (i < $scope.gLifePicUrls.length - 1) {
            $scope.gLifePicUrl += ",";
          }
        }

        var base64Arry = $scope.displayPicBase64Data + "," +
          ($scope.tourGuideCertificationPicBase64Data === "" ? "" : ($scope.tourGuideCertificationPicBase64Data + ",")) +
          $scope.gLifePicUrl;
        // 上传图片
        $$UploadImageService.uploadImage(base64Arry).then(function(res) {
          $scope.authguideData.displayPic = res.data.pic.split(",")[0];
          $scope.authguideData.tourGuideCertificationPic = ($scope.tourGuideCertificationPicBase64Data === "" ? "" : res.data.pic.split(",")[1]);
          $scope.authguideData.lifePic = "";
          for (var i = ($scope.tourGuideCertificationPicBase64Data === "" ? 1 : 2); i < res.data.pic.split(",").length; i++) {
            $scope.authguideData.lifePic = $scope.authguideData.lifePic + res.data.pic.split(",")[i] + ",";
          }
          $scope.authguideData.lifePic = $scope.authguideData.lifePic.substr(0, $scope.authguideData.lifePic.length - 1);
          // 提交表单数据
          $$UserAuthService.authguide($scope.authguideData).then(function(res) {
            $ionicLoading.show({
              template: res.msg,
              noBackdrop: true,
              duration: 1500
            });
            $timeout(function() {
              $location.path("authselect");
            }, 1500);
          });

        });

      }
    };



    // 复选服务内容
    $scope.cheackboxServerCate = function(index, id) {
      $scope.authguideDataServerCate[index].checked = !$scope.authguideDataServerCate[index].checked;
      var datastr = "";
      for (var i in $scope.authguideDataServerCate) {
        if ($scope.authguideDataServerCate[i].checked) {
          datastr = datastr + $scope.authguideDataServerCate[i].id + ",";
        }
      }
      datastr = datastr.substr(0, datastr.length - 1);
      $scope.authguideData.hotId = datastr;
    };


    $scope.citypickmodal = {};
    $ionicModal.fromTemplateUrl('citypicker.html', {
      scope: $scope,
      animation: 'slide-in-top'
    }).then(function(modal) {
      $scope.citypickmodal = modal;
      // $scope.citypickmodal.show();
    });


    //监听离开页面时关闭model
    $scope.$on("$ionicParentView.beforeLeave", function() {
      console.info("TrafficSignCtrl--$ionicView.beforeLeave ");
      // if(){

      // }
      // $location.path("getmoney");
      $scope.citypickmodal.hide();
    });

    $scope.getmoneyway = function(wayid) {
      $scope.citypickmodal.show();

    };

    $scope.closeModal = function() {
      $scope.citypickmodal.hide();
    };

    $scope.provincedatalist = [];
    $scope.citydatalist = [];
    $scope.cityselectresult = {
      val: "serviceCity",
      id: null,
      name: "请选择",
      province: {
        id: null,
        name: null
      },
      city: {
        id: null,
        name: null
      }
    };

    // 获取省份列表
    $$CityService.getprovince()
      .then(function(res) {
        $scope.provincedatalist = res.data;
      });

    $scope.cp_selectprovince = function(province) {
      $scope.cityselectresult.province.id = province.id;
      $scope.cityselectresult.province.name = province.name;
      // 获取城市列表
      $$CityService.getcitys(province.id)
        .then(function(res) {
          $scope.citydatalist = res.data;
          $ionicScrollDelegate.scrollTop(0);
        });
    };

    $scope.cp_selectcity = function(city) {
      $scope.cityselectresult.city.id = city.id;
      $scope.cityselectresult.city.name = city.city;
    };


    $scope.sureSelectCityResult = function() {
      if ($scope.cityselectresult.city.id != null) {
        if ($scope.cityselectresult.val == "region") {
          $scope.authguideData.region = $scope.cityselectresult.city.id;
          $scope.authguideData.regionName = $scope.cityselectresult.province.name + $scope.cityselectresult.city.name;
        }
        if ($scope.cityselectresult.val == "serviceCity") {
          $scope.authguideData.serviceCity = $scope.cityselectresult.city.id;
          $scope.authguideData.serviceCityName = $scope.cityselectresult.city.name;
        }
      }
      $scope.citypickmodal.hide();
    };

    $scope.reselectprovince = function() {
      $scope.cityselectresult.province.id = null;
      $scope.cityselectresult.province.name = null;
      $scope.cityselectresult.city.id = null;
      $scope.cityselectresult.city.name = null;
    };

    $scope.openCitySelectModel = function(val) {
      $scope.cityselectresult.val = val;
      $scope.citypickmodal.show();
    };

    $scope.gJobData = [];

    // 获取工作
    $$JobService.getJobs()
      .then(function(res) {
        $scope.gJobData = res.data.data;
      });

    // 图片数组
    $scope.gLifePicUrls = [];

    $scope.substep1 = function() {
      if ($scope.validForm1()) {
        $scope.step = 2;
        $scope.topstep = 2;
      }
    };



    // 跳到第几步
    $scope.tostep = function(ss) {
      if (ss > $scope.topstep) {
        return;
        // if ($scope.validForm1()) {
        //   $scope.step = ss;
        // }
      }
      if (ss == 1) {
        $scope.step = ss;
      }
      if (ss == 2) {
        if ($scope.validForm2() && $scope.validForm2() && $scope.validForm3()) {
          $scope.step = ss;
        }
      }
    };


    $scope.validForm1 = function() {
      // return true;
      if ($scope.authguideData.job === '请选择') {
        $rootScope.alertPopup("请正确输入职业");
        $scope.step = 1;
        return false;
      }
      if ($scope.authguideData.region === '') {
        $rootScope.alertPopup("请正确输入地址");
        $scope.step = 1;
        return false;
      }
      // if (!checkPhone($scope.authguideData.contactPhone)) {
      //   $rootScope.alertPopup("请正确输入联系电话");
      //   $scope.step = 1;
      //   return false;
      // }
      if (!checkText($scope.authguideData.weChat)) {
        $rootScope.alertPopup("请正确输入微信号");
        $scope.step = 1;
        return false;
      }
      if ($scope.displayPicBase64Data === "") {
        $rootScope.alertPopup("请添加1张封面图片");
        $scope.step = 1;
        return false;
      }
      if ($scope.gLifePicUrls.length === 0) {
        $rootScope.alertPopup("请添加1-6张生活照片");
        $scope.step = 1;
        return false;
      }
      return true;
    };

    $scope.validForm2 = function() {
      // return true;
      if ($scope.authguideData.serviceCity == '-1') {
        $rootScope.alertPopup("请正确选择服务城市");
        $scope.step = 2;
        return false;
      }
      if (!checkText($scope.authguideData.serviceRoute)) {
        $rootScope.alertPopup("请正确输入擅长路线");
        $scope.step = 2;
        return false;
      }
      // console.log($scope.authguideData.serviceContent);
      // console.log(checkText($scope.authguideData.serviceContent));
      if (!checkText($scope.authguideData.serviceContent)) {
        $rootScope.alertPopup("请正确输入服务内容");
        $scope.step = 2;
        return false;
      }
      if (!checkText($scope.authguideData.introduce)) {
        $rootScope.alertPopup("请正确输入个人介绍");
        $scope.step = 2;
        return false;
      }
      if (!checkPrice($scope.authguideData.servicePrice) || $scope.authguideData.servicePrice <= 0) {
        $rootScope.alertPopup("请正确输入价格");
        $scope.step = 2;
        return false;
      }
      // if (!$scope.tourGuideCertificationPicBase64Data) {
      //   $rootScope.alertPopup("请正确输入导游证");
      //   return;
      // }
      return true;
    };


    // 生活照按钮点击
    $scope.selectImgLifePic = function() {
      if ($scope.gLifePicUrls.length < 6) {    
        if ($rootScope.config.isWebView) { // cordova app端中
          $scope.appphoto_lifeimgsel();
        } else { // 浏览器中
          $("#selectImgLifePicInput").trigger('click');
        }
      }
    };


    $scope.appphoto_lifeimgsel = function() {
      // 选择上传方式
      var hideSheet_appphoto_lifeimgsel = $ionicActionSheet.show({
        buttons: [
          { text: '相机拍照' },
          { text: '手机相册' }
        ],
        // destructiveText: 'Delete',
        titleText: '选择图片上传方式',
        cancelText: '取消',
        cancel: function() {
          // add cancel code..
        },
        buttonClicked: function(index) {
          if (index == 0) {
            // 调用摄像头拍照
            var options = {
              quality: 50,
              destinationType: Camera.DestinationType.DATA_URL,
              sourceType: Camera.PictureSourceType.CAMERA,
              allowEdit: false,
              encodingType: Camera.EncodingType.JPEG,
              // targetWidth: 100,
              // targetHeight: 100,
              popoverOptions: CameraPopoverOptions,
              saveToPhotoAlbum: false,
              correctOrientation: true
            };
            $$cordovaCamera.getPicture(options).then(function(imageData) {
            hideSheet_appphoto_lifeimgsel();
            $scope.gLifePicUrls.push({ src: "data:image/jpeg;base64," + imageData });
            }, function(err) {
              // error
            });
          } else if (index == 1) {
            // 调用手机相册
            $$cordovaImagePicker.getPictures({
                maximumImagesCount: 1,
                // width: 100,
                // height: 100,
                quality: 50
              })
              .then(function(results) {
                // console.log(results);
                var image = new Image();
                image.src = results[0];
                image.onload = function() {
                  var canvas = document.createElement("canvas");
                  canvas.width = this.width;
                  canvas.height = this.height;
                  var ctx = canvas.getContext("2d");
                  ctx.drawImage(this, 0, 0, this.width, this.height);
                  var ext = this.src.substring(this.src.lastIndexOf(".") + 1).toLowerCase();
                  var base64 = canvas.toDataURL("image/" + ext);
                  hideSheet_appphoto_lifeimgsel();
                  $scope.gLifePicUrls.push({ src: base64 });
                };
              }, function(error) {});
          }
        }
      });
    };


    // 生活照input监听
    document.getElementById("selectImgLifePicInput").addEventListener('change', function(argument) {
      var file = this.files[0];
      //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
      if (!/image\/\w+/.test(file.type)) {
        $rootScope.alertPopup('请确保文件为图像类型');
        return false;
      } else {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e) {
          $scope.gLifePicUrls.push({ src: this.result });
          // $rootScope.alertPopup($scope.gLifePicUrls.length);
          $scope.$apply();
        };
      }
    }, false);


    // 上传封面按钮点击
    $scope.selectImgDisplayPic = function() {

      if ($rootScope.config.isWebView) { // cordova app端中
        $scope.appphoto_DisplayPic();
      } else { // 浏览器中
        $("#selectImgDisplayPicInput").trigger('click');
      }

    };

    $scope.appphoto_DisplayPic = function() {
      // 选择上传方式
      var hideSheet_appphoto_DisplayPic = $ionicActionSheet.show({
        buttons: [
          { text: '相机拍照' },
          { text: '手机相册' }
        ],
        // destructiveText: 'Delete',
        titleText: '选择图片上传方式',
        cancelText: '取消',
        cancel: function() {
          // add cancel code..
        },
        buttonClicked: function(index) {
          if (index == 0) {
            // 调用摄像头拍照
            var options = {
              quality: 50,
              destinationType: Camera.DestinationType.DATA_URL,
              sourceType: Camera.PictureSourceType.CAMERA,
              allowEdit: false,
              encodingType: Camera.EncodingType.JPEG,
              // targetWidth: 100,
              // targetHeight: 100,
              popoverOptions: CameraPopoverOptions,
              saveToPhotoAlbum: false,
              correctOrientation: true
            };
            $$cordovaCamera.getPicture(options).then(function(imageData) {
              hideSheet_appphoto_DisplayPic();
              $scope.displayPicBase64Data = "data:image/jpeg;base64," + imageData;
            }, function(err) {
              // error
            });
          } else if (index == 1) {
            // 调用手机相册
            $$cordovaImagePicker.getPictures({
                maximumImagesCount: 1,
                // width: 100,
                // height: 100,
                quality: 50
              })
              .then(function(results) {
                // console.log(results);
                var image = new Image();
                image.src = results[0];
                image.onload = function() {
                  var canvas = document.createElement("canvas");
                  canvas.width = this.width;
                  canvas.height = this.height;
                  var ctx = canvas.getContext("2d");
                  ctx.drawImage(this, 0, 0, this.width, this.height);
                  var ext = this.src.substring(this.src.lastIndexOf(".") + 1).toLowerCase();
                  var base64 = canvas.toDataURL("image/" + ext);
                  hideSheet_appphoto_DisplayPic();
                  $scope.displayPicBase64Data = base64;
                };
              }, function(error) {});
          }
        }
      });
    };

    // 上传封面input监听
    document.getElementById("selectImgDisplayPicInput").addEventListener('change', function(argument) {
      var file = this.files[0];
      //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
      if (!/image\/\w+/.test(file.type)) {
        $rootScope.alertPopup('请确保文件为图像类型');
        return false;
      } else {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e) {
          $scope.displayPicBase64Data = this.result;
          $scope.$apply();
        };
      }
    }, false);



    // 上传导游证按钮点击
    $scope.selectImgGuideCertificatePic = function() {
      if ($rootScope.config.isWebView) { // cordova app端中
        $scope.appphoto_GuideCertificatePic();
      } else { // 浏览器中
        $("#selectImgGuideCertificatePicInput").trigger('click');
      }

    };

    $scope.appphoto_GuideCertificatePic  = function() {
      // 选择上传方式
      var hideSheet_appphoto_GuideCertificatePic = $ionicActionSheet.show({
        buttons: [
          { text: '相机拍照' },
          { text: '手机相册' }
        ],
        // destructiveText: 'Delete',
        titleText: '选择图片上传方式',
        cancelText: '取消',
        cancel: function() {
          // add cancel code..
        },
        buttonClicked: function(index) {
          if (index == 0) {
            // 调用摄像头拍照
            var options = {
              quality: 50,
              destinationType: Camera.DestinationType.DATA_URL,
              sourceType: Camera.PictureSourceType.CAMERA,
              allowEdit: false,
              encodingType: Camera.EncodingType.JPEG,
              // targetWidth: 100,
              // targetHeight: 100,
              popoverOptions: CameraPopoverOptions,
              saveToPhotoAlbum: false,
              correctOrientation: true
            };
            $$cordovaCamera.getPicture(options).then(function(imageData) {
              hideSheet_appphoto_GuideCertificatePic();
              $scope.tourGuideCertificationPicBase64Data = "data:image/jpeg;base64," + imageData;
            }, function(err) {
              // error
            });
          } else if (index == 1) {
            // 调用手机相册
            $$cordovaImagePicker.getPictures({
                maximumImagesCount: 1,
                // width: 100,
                // height: 100,
                quality: 50
              })
              .then(function(results) {
                // console.log(results);
                var image = new Image();
                image.src = results[0];
                image.onload = function() {
                  var canvas = document.createElement("canvas");
                  canvas.width = this.width;
                  canvas.height = this.height;
                  var ctx = canvas.getContext("2d");
                  ctx.drawImage(this, 0, 0, this.width, this.height);
                  var ext = this.src.substring(this.src.lastIndexOf(".") + 1).toLowerCase();
                  var base64 = canvas.toDataURL("image/" + ext);
                  hideSheet_appphoto_GuideCertificatePic();
                  $scope.tourGuideCertificationPicBase64Data = base64;
                };
              }, function(error) {});
          }
        }
      });
    };


    // 上传导游证input监听
    document.getElementById("selectImgGuideCertificatePicInput").addEventListener('change', function(argument) {
      var file = this.files[0];
      //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
      if (!/image\/\w+/.test(file.type)) {
        $rootScope.alertPopup('请确保文件为图像类型');
        return false;
      } else {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e) {
          $scope.tourGuideCertificationPicBase64Data = this.result;
          $scope.$apply();
        };
      }
    }, false);


    $scope.removeLifePic = function(removeLifePicIndex) {
      var confirmPopup = $ionicPopup.confirm({
        title: '删除图片',
        template: '是否删除该图片',
        buttons: [
          { text: '取消' },
          {
            text: '<b>确定</b>',
            type: 'button-assertive',
            onTap: function(e) {
              $scope.gLifePicUrls.splice(removeLifePicIndex, 1); //清空数组
            }
          },
        ]
      });
    };

    $scope.removeselectImgGuideCertificatePic = function() {
      var confirmPopup = $ionicPopup.confirm({
        title: '删除图片',
        template: '是否删除该图片',
        buttons: [
          { text: '取消' },
          {
            text: '<b>确定</b>',
            type: 'button-assertive',
            onTap: function(e) {
              $scope.tourGuideCertificationPicBase64Data = "";
            }
          },
        ]
      });
    };

  });
